﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace HamcoWcs.Main.Controllers
{
    /// <summary>
    /// 基础控制器
    /// </summary>
    //[NonController]
    [ApiController]
    [Route("[controller]/[action]")]
    public abstract class BasicController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        public abstract string ControllerName { get; }
        /// <summary>
        /// log接口
        /// </summary>
        protected readonly ILoggerService _logger;
        /// <summary>
        /// Mapper接口
        /// </summary>
        protected readonly IMapper _mapper;
        /// <summary>
        /// wcs数据库上下文
        /// </summary>
        protected readonly WcsDbContext _wcsDbContext;

        /// <summary>
        /// 默认的前端返回Json配置
        /// </summary>
        protected static JsonSerializerSettings DEFAULT_JSON_SETTINGS = new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore,
        };

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        /// <param name="wcsDbContext"></param>
        public BasicController(ILoggerService logger, IMapper mapper, WcsDbContext wcsDbContext)
        {
            _logger = logger;
            _mapper = mapper;
            _wcsDbContext = wcsDbContext;
        }

        #region [CRUD Failure Result]

        private static ForeEndResult CREATE_FAILUER_RESULT =
           ForeEndResult.Fail("新增失败");

        private static ForeEndResult DELETE_FAILUER_RESULT =
            ForeEndResult.Fail("删除失败");

        private static ForeEndResult UPDATE_FAILUER_RESULT =
            ForeEndResult.Fail("修改失败");

        private static ForeEndResult QUERY_FAILUER_RESULT =
            ForeEndResult.Fail("查询失败");

        private static ForeEndResult UNKNOWN_EXCEPTION_RESULT =
            ForeEndResult.Fail("未知异常");

        /// <summary>返回新增失败</summary>
        protected IActionResult CreateFailureResult() => Json(CREATE_FAILUER_RESULT, DEFAULT_JSON_SETTINGS);
        /// <summary>返回删除失败</summary>
        protected IActionResult DeleteFailureResult() => Json(DELETE_FAILUER_RESULT, DEFAULT_JSON_SETTINGS);
        /// <summary>返回修改失败</summary>
        protected IActionResult UpdateFailureResult() => Json(UPDATE_FAILUER_RESULT, DEFAULT_JSON_SETTINGS);
        /// <summary>返回查询失败</summary>
        protected IActionResult QueryFailureResult() => Json(QUERY_FAILUER_RESULT, DEFAULT_JSON_SETTINGS);
        /// <summary>返回未知异常</summary>
        protected IActionResult UnknownExceptionResult() => Json(UNKNOWN_EXCEPTION_RESULT, DEFAULT_JSON_SETTINGS);
        #endregion


        /// <summary>
        /// 返回警告信息
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        protected IActionResult Warning(WarningException e)
            => Json(ForeEndResult.Fail(e.Message), DEFAULT_JSON_SETTINGS);


        ///<summary>添加操作日志</summary>
        protected virtual void AddOperationLog(string userName, string msg, string unitId = "", string deviceName = "", [CallerMemberName] string methodName = "")
        {
            try
            {
                _logger.AddOperationLog(userName, ControllerName, methodName, unitId, deviceName, msg);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message, $"{methodName}->AddOperationLog");
            }
        }

        ///<summary>添加系统日志<br/>Controller -> Method : message</summary>
        protected virtual void AddSystemLog(string msg, [CallerMemberName] string methodName = "")
        {
            try
            {
                _logger.AddSystemErrorLog($"{ControllerName}->{methodName}:{msg}");
            }
            catch (Exception ex)
            {
                //Debug.Assert(false);
            }
        }

        ///<summary>添加系统错误日志</summary>
        protected IActionResult Error(Exception e, string controller, string message = "", [CallerMemberName] string methodName = "")
        {
            _logger.AddSystemErrorLog($"{controller}->{methodName}:{e.Message}");
            return Json(ForeEndResult.Fail(message));
        }
    }
}
